<?php
	session_start();
	$message=null;

	require('config/mysql.config.inc');
	$mysqli = new mysqli($host, $username, $password, $db);	
		/*
if($result['firstname'] != "" && $result['lastname'] != "" && $result['city'] != "" && $result['state'] != "" && $result['zip'] != "" && $result['telephone'] != ""){
		
		}
*/
	
	
	$uid=null;
	if (isset($_SESSION['user'])){
		$username= $mysqli->query("SELECT uid FROM Users WHERE email='".$_SESSION['user']."'");
		$username= $username->fetch_row();
		$uid=$username[0];
	} else {
		$message=$message. "Please log in.";
	}
	
	function makeThumb($imgpath){
		$img = imagecreatefromjpeg($imgpath);
		$imgpathexplode = explode("/", $imgpath);
		$width = imagesx($img);
		$height = imagesy($img);

		$thumb_height = 200;

		$new_height = $thumb_height;
		$new_width = floor($width * ($thumb_height/$height));

		$new_img = imagecreatetruecolor($new_width, $new_height);

		imagecopyresampled($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

		$return = imagejpeg($new_img, "furniturethumbs/". $imgpathexplode[1]);
		
		imageDestroy($img);
		imageDestroy($new_img);
	}	
	
	function validQuantity($qty){
		$pattern = "/^[0-9]{1,2}$/";		
		return preg_match($pattern, $qty);
	}
	
	//A FUNCTION TO SEE IF THE CURRENT WISHLIST BELONGS TO THE CURRENT LOGGED IN USER
	//return true if the $id of the wishlist belongs to the currently logged in user
	function isProperWishlist($id, $uid){
		require('config/mysql.config.inc');
		$mysqli = new mysqli($host, $username, $password, $db);	
		
		$query="SELECT * FROM Wishlists WHERE uid='".$uid."'";
		$result = $mysqli->query($query);
		$belongs=false;
		while ($list = $result->fetch_assoc()) {
			if ($id == $list['wishlistid']) {
				$belongs=true;
			}	
		}
		return $belongs;
	}

//process updates and deletes
if (isset($_POST['wishlistid']) && isset($_POST['submit'])){
	if (isProperWishlist($_POST['wishlistid'],$uid)){
		//is it update or delete?
		if ($_POST['submit']=="Update"){
			//process the update
			$query="UPDATE Wishlists SET wname=? WHERE wishlistid = ?";
			$stmt= $mysqli->stmt_init();
			if ($stmt->prepare($query)){
				$stmt->bind_param('si',$_POST['name'],$_POST['wishlistid']);
				$stmt->execute();
			}
			if($stmt->affected_rows>0){
				$message=$message."Wishlist updated successfully";
			} else {
				$message=$message."Wishlist update failed";
			}
		} elseif ($_POST['submit']=="Delete") {
			if (isset($_POST['confirm'])){
				$query="DELETE FROM Wishlists WHERE wishlistid = ?";
				$stmt= $mysqli->stmt_init();
				if ($stmt->prepare($query)){
					$stmt->bind_param('i',$_POST['wishlistid']);
					$stmt->execute();
				}
				
				$query="DELETE FROM InWishlist WHERE wishlistid = ?";
				$stmt2= $mysqli->stmt_init();
				if ($stmt2->prepare($query)){
					$stmt2->bind_param('i',$_POST['wishlistid']);
					$stmt2->execute();
				}
				if($stmt->affected_rows>0){
						$message=$message."Wishlist deleted successfully";
				} else {
						$message=$message."Wishlist delete failed";
				}
			}else{$message= $message."Please click the checkbox to confirm the deletion of your wishlist.";}
		}
	} else {
		$message=$message." The wishlist you are trying to edit does not belong to you. ";
	}
}

//process createNew
if (isset($_POST['submitNew']) && $uid!=null){
	//Make sure that the name doesn't already exist for this user (and only for this user)	
	$query="SELECT wname FROM Wishlists WHERE uid='".$uid."' ORDER BY wname";
	$result = $mysqli->query($query);
	$unique=true;
	while ($name = $result->fetch_assoc()) {
		if ($_POST['name'] == $name['wname']) {
			$unique=false;
		}	
	}

	//process the insert
	if ($unique) {
	$query="INSERT INTO Wishlists VALUES(null,'".$uid."',?)";
	$stmt= $mysqli->stmt_init();
	if ($stmt->prepare($query)){
		$stmt->bind_param('s',$_POST['name']);
		$stmt->execute();
	}
	if($stmt->affected_rows>0){
		$message=$message."Wishlist created successfully. ";
	} else {
		$message=$message."Wishlist creation failed. ";
	}
	} else {
		$message=$message." Wishlist creation failed. The name of your wishlist was not unique. ";		
	}
}
	
//process update for wishlist items
if (isset($_POST['submit2']) && $uid!=null){
	//check to see if remove is checked	
	if (isset($_POST['remove'])){
		$mysqli->autocommit(false);
		
		$query="DELETE FROM CustomPieces WHERE customid=?";
		$stmt= $mysqli->stmt_init();
		if ($stmt->prepare($query)){
			$stmt->bind_param('s',$_POST['customid']);
			$stmt->execute();
		}

		$query="DELETE FROM InWishlist WHERE customid=?";
		$result2 = $mysqli->query($query);
		$stmt2= $mysqli->stmt_init();
		if ($stmt2->prepare($query)){
			$stmt2->bind_param('s',$_POST['customid']);
			$stmt2->execute();
		}
		
		if ($stmt->affected_rows>0 && $stmt2->affected_rows>0) {
			$mysqli->commit();
			$message=$message." Deletion successful. ";
		} else {
			$mysqli->rollback();
			$message=$message." Deletion failed. ";
		}
		$mysqli->autocommit(true);
	} elseif ($uid!=null) {
		//remove not set --> process updates
		//process the move to and the quantity
		if (validQuantity($_POST['qty'])) {
			//invariant: the wname is unique for within any user
			
			$query= "SELECT wishlistid FROM Wishlists WHERE wname='".$_POST['newwishlistid']."' AND uid='".$uid."'";
			$temp= $mysqli->query($query);
			$temp= $temp->fetch_row();
			$newwishlistid= $temp[0];
			
			//TODO: if this exact item is already in the new wishlist
			//if so, remove from old wishlist and update quantity in new
			//else remove from old wishlist and add to new
			if (false) {
				//remove from old wishlist and update quantity in new
			} else {
				//remove from old wishlist and add to new
				if (isProperWishlist($newwishlistid,$uid)){			
					$query="UPDATE InWishlist SET wishlistid='".$newwishlistid."',quantity=? WHERE customid=?";
					$stmt= $mysqli->stmt_init();
					if ($stmt->prepare($query)){
						$stmt->bind_param('ii',$_POST['qty'],$_POST['customid']);
						$stmt->execute();
					}	

					if ($stmt->affected_rows>0){
						$message=$message."Piece update successful.";		
					} else {
						$message=$message."Piece update failed.";
					}
				} else {
					$message=$message." The wishlist you are trying to edit does not belong to you. ";
				}
			}
		} else {
				$message=$message." Piece update failed: enter a value for the quantity 0-99. ";
		}
	}
}	

//process the sending of an email
if (isset($_POST['email_submit']) && $uid!=null){

	//CAPTCHA checking
		//Go here for help editing captcha: http://recaptcha.net/plugins/php/
		require_once('includes/recaptchalib.php');
		require_once('config/recaptcha.config.inc');
		$resp = recaptcha_check_answer($privatekey,
									$_SERVER["REMOTE_ADDR"],
									$_POST["recaptcha_challenge_field"],
									$_POST["recaptcha_response_field"]);
		
	if (!$resp->is_valid) {
		$message.= "The reCAPTCHA wasn't entered correctly. Please go back and try it again.";
	}
	//END CAPTCHA checking
	
	else{
		//Check if all of user's personal info is filled out
		$query="SELECT * FROM Users WHERE uid='".$uid."'";
		$result= $mysqli->query($query);
		$isInfoThere= $result->fetch_assoc();
		
		if($isInfoThere['firstname'] != "" && $isInfoThere['lastname'] != "" && $isInfoThere['city'] != "" && $isInfoThere['state'] != "" && $isInfoThere['zip'] != "" && $isInfoThere['telephone'] != ""){				
		require('includes/my_email.php'); //imports $emailAddress
		$to = $emailAddress;
		$wishid= $_POST['list'];
		
		$query="SELECT wname FROM Wishlists WHERE wishlistid= '".$wishid."'";
		$wishname= $mysqli->query($query);	
		$wishname=$wishname->fetch_row();
		$wishname=$wishname[0];
		
		$query="SELECT COUNT(*) FROM Wishlists NATURAL JOIN InWishlist NATURAL JOIN CustomPieces WHERE uid = '".$uid."' AND wishlistid= '".$wishid."'";
		$numPieces= $mysqli->query($query);	
		$numPieces=$numPieces->fetch_row();
		$numPieces=$numPieces[0];
		
		$query="SELECT * FROM Wishlists NATURAL JOIN InWishlist NATURAL JOIN CustomPieces WHERE uid = '".$uid."' AND wishlistid= '".$wishid."'";
		$pieces= $mysqli->query($query);			
		
		$i=1;
		$output= $_SESSION['user']." is sending their Wishlist: ". $wishname;
		$output.="<br/><br/>There are $numPieces pieces of furniture in this wishlist.<br/><br/>";
		while ($piece= $pieces->fetch_assoc()) {		
			$output.= "Item #".$i.":<br/>";
			//modelno, finishid, materialid,shapeidlength,width,height, quantity
			
			$output.= "Model No.: ".$piece['modelno'];
			
			$query="SELECT mname FROM MaterialTypes WHERE materialid = '".$piece['materialid']."'";
			$temp= $mysqli->query($query);	
			$temp=$temp->fetch_row();
			$mname=$temp[0];		
			
			$query="SELECT fname FROM FinishTypes WHERE finishid = '".$piece['finishid']."'";
			$temp= $mysqli->query($query);	
			$temp=$temp->fetch_row();
			$fname=$temp[0];
			
			$query="SELECT sname FROM ShapeTypes WHERE shapeid = '".$piece['shapeid']."'";
			$temp= $mysqli->query($query);	
			$temp=$temp->fetch_row();
			$sname=$temp[0];
			
			$output.= "<br/>Material: ".$mname;
			$output.= "<br/>Finish: ".$fname;
			$output.= "<br/>Shape: ".$sname;
			
			$output.= "<br/>Length: ".$piece['length']."\"<br/>";			
			$output.= "Width: ".$piece['width']."\"<br/>";					
			$output.= "Height: ".$piece['height']."\"<br/>";					
			$output.= "Qty: ".$piece['quantity'];				

			$i++;
			$output.= "<br/><br/>";
		}
		
		$output.= "Notes From The Customer:<br/> " . $_POST['message'];
		$output.= "<br/><br/>Customer Contact Information:<br/> ";
		//TODO: create contact information from Users table
		
		$query="SELECT email,firstname,lastname,city,state,zip,telephone FROM Users WHERE uid ='".$uid."'";
		$user= $mysqli->query($query);	
		$user=$user->fetch_assoc();
		$output.= "First Name: ".$user['firstname']."<br/>";
		$output.= "Last Name: ".$user['lastname']."<br/>";
		$output.= "City Name: ".$user['city']."<br/>";
		$output.= "State: ".$user['state']."<br/>";
		$output.= "Zip: ".$user['zip']."<br/>";
		$output.= "Telephone: ".$user['telephone']."<br/>";		
		
		$subject = $_SESSION['user']." is sending their Wishlist: ". $wishname.".";
				
		//send in HTML
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";		
		
		$headers.= "From: " . $user['email']; 
		$sent = mail($to, $subject, $output, $headers);
		
		//this $message should be displayed lower.
		if ($sent) {
			$message = "Your wishlist was sent successfully.";
		} 
		else {
			$message = "There was an error sending your wishlist. Please try again.";
		}
	}else{
		$message= "Please enter all of your account information before you send in a wishlist.";
	}
}
}

	$page= 'Wishlist';
	include ('includes/header.php');
	include('includes/menubar.php');
	print("\n");
?>

<div class="body_content">
	
<?php
if (isset($_SESSION['user'])){
	print("<h3>Your Wishlists: </h3>");
//List all of the wishlists for this user
	//Query the database for this user's wishlists
	//$query="SELECT * FROM CustomPieces NATURAL JOIN (inWishList NATURAL JOIN Wishlists) where uid = '" . $uid . "'";
	$query="SELECT * FROM Wishlists where uid = '".$uid."' ORDER BY wname";
	$wishlists= $mysqli->query($query);
	$checkwishlists= $mysqli->query($query);
	
	//invariant: result holds the data from every wishlist that belongs to that user.
	
	
	//store the wishlists in an array
	//$wishlists = query results (associative array)
	
	//For each wishlist allow the user to edit its name or to delete it
	//Upon clicking a wishlist, this page should reload with the wishlist's content enumerated
		?>	<div class="wishlist-form"><?php
			
			if(!($list= $checkwishlists->fetch_row())){
				$message= "You currently have no wishlists. To create one, use the form below.";
			}

			print("<p>$message</p>");
			while ($list= $wishlists->fetch_assoc()) {
				//$list is an associative array
				print("\n");
				?>
				<form method="post" action="wishlist.php">
					<fieldset>Change wishlist name: 
						<?php
							print("<input type=\"text\" name=\"name\" value=\"".$list['wname']."\" size=\"20\" />");
							print("<input type=\"submit\" name=\"submit\" value=\"Update\" />");
							$id=null;
							if (isset($_GET['id']) || isset($_POST['wishlistid'])){
								//check to see if this wishlist id belongs to this user
								if (isset($_GET['id'])){
									$id=$_GET['id'];
								} else {
									$id=$_POST['wishlistid'];	
								}
							}
							if ($id == $list['wishlistid']) {
								if (isset($_POST['toggle']) && $_POST['toggle']=="Open Wishlist" || isset($_GET['id'])) {
									print("<input class=\"toggle\" type=\"submit\" name=\"toggle\" value=\"Close Wishlist\" />	");
								} else {
									print("<input class=\"toggle\" type=\"submit\" name=\"toggle\" value=\"Open Wishlist\" />	");
								}
							} else {
								print("<input class=\"toggle\" type=\"submit\" name=\"toggle\" value=\"Open Wishlist\" />	");
							}
							
							print("<input class=\"name\" type=\"hidden\" name=\"wishlistid\" value=\"".$list['wishlistid']."\"/>");
						?>
						Delete: <input type="checkbox" name="confirm" value="yes">
						<input type="submit" name="submit" value="Delete" />
					</fieldset>
				</form>
				<?php
			}

	print("\n");
//Form to create a new wishlist
?>
		</div>
		<h3>Create a New Wishlist: </h3>
		<div class="wishlist-form">
			<form method="post" action="wishlist.php">
				<fieldset>
					<input type="text" name="name" value="Wishlist Name" size="20" />
					<input type="submit" name="submitNew" value="Create" />
				</fieldset>
			</form>
		</div>
		
		<div id="wishlist-holder">
<?php
	//If GET(wishlistid) is set 
	if (isset($_GET['id']) || (isset($_POST['toggle']) && $_POST['toggle']=="Open Wishlist" && isset($_POST['wishlistid']))){
		//check to see if this wishlist id belongs to this user
		if (isset($_GET['id'])){
			$id=$_GET['id'];
		} else {
			$id=$_POST['wishlistid'];	
		}
		
		$query="SELECT wname FROM Wishlists WHERE wishlistid = '".$id."'";
		
		$wname= $mysqli->query($query);
		$wname=$wname->fetch_row();
		$wname=$wname[0];
		print("\t\t<h3>Displaying Wishlist: ".$wname."</h3>\n"); 	
		
		//get a list of all of the wishlists, for later
		$query="SELECT * FROM Wishlists where uid = '".$uid."' ORDER BY wname";
		$wishlists= $mysqli->query($query);		
		
		//list all of that wishlist's items
		//query the ContainsPieces for the specified wishlistid
		$query="SELECT * FROM CustomPieces NATURAL JOIN InWishlist WHERE wishlistid = '".$id."'";
		//store the pieces in an array
		$pieces= $mysqli->query($query);		
		
		//for each piece, display its info
		while ($piece= $pieces->fetch_assoc()) {

				//picture, description/details, links to edit item, remove from wishlist, update quantity, move to another wishlist (dropdown menu)
					//if user clicks edititem, load edititem.php

					//if user clicks remove, reload the page with POST(remove-itemid) set (to anything)
					//if user clicks update, reload the page with POST(update-itemid) set to the quantity amount
					//if user clicks move, reload the page with POST(move-itemid) set to the quantity amount and POST(newwishlistid) set to the new wishlist's id
?>
			<div class="wishlist-piece">
				<form method="post" action="wishlist.php">
					<fieldset>
						<div class="wishlist-piece-left">
							<?php 
								//hidden form value
								print("<input type=\"hidden\" name=\"customid\" value=\"".$piece['customid']."\"/>\n ");
								
								$query="SELECT pname,description,photourl FROM Pieces WHERE modelno= '".$piece['modelno']."'";
								$original= $mysqli->query($query);
								$original= $original->fetch_assoc();
								
								makeThumb($original['photourl']);
								$url = explode("/", $original['photourl']);
								print("\t\t\t\t\t\t\t<div class=\"wishlist-piece-img\">\n\t\t\t\t\t\t\t\t<a href=\"edititem.php?customid=".$piece['customid']."\"><img src=\"furniturethumbs/".$url[1]."\"/></a> ");
								print("<br/>\n\t\t\t\t\t\t\tClick picture for more details...\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t");
								//print($original['description']." |"); 

								print("<div class=\"wishlist-piece-name\">". $original['pname'] ."\n\t\t\t\t\t\t\t</div>\n ");
							?>
						</div>
						<div class="wishlist-piece-right">
							<?php
								print("Qty: <input type=\"text\" size=\"3\" name=\"qty\" value=\"".$piece['quantity']."\"> <br/> ");	
							?>	
							Remove: <input type="checkbox" name="remove" value="yes"> <br/>
							Move to: 
								<select name="newwishlistid">
								<?php 
									//get a list of all of the wishlists
									$query="SELECT * FROM Wishlists where uid = '".$uid."' ORDER BY wname";
									$wishlists= $mysqli->query($query);	
									while ($list= $wishlists->fetch_assoc()) {
										if ($wname == $list['wname']){
											print("<option value=\"".$list['wname']."\" selected>".$list['wname']."</option>\n\t\t\t\t\t\t\t\t");											
										} else {
											print("<option value=\"".$list['wname']."\">".$list['wname']."</option>\n\t\t\t\t\t\t\t\t");
										}
									}
									print("\n");
								?>
								</select>
							<br/>
							<input type="submit" name="submit2" value="Update" />
							<br/><br/>
							<?php	print("<a href=\"edititem.php?customid=".$piece['customid']."\">Edit Item Details</a> <br/>  ");	?>
						</div>
					</fieldset>
				</form>
			</div>
<?php
		}
	}
//Create a form to send a wishlist to DFS
?>
	</div>
	
<?php
if((isset($_POST['toggle']) && $_POST['toggle']=="Open Wishlist" && isset($_POST['wishlistid']))){
$query="SELECT * FROM Wishlists where uid = '".$uid."' ORDER BY wname";
$beforeordering= $mysqli->query($query);

	if($orderlist= $beforeordering->fetch_row()){
	echo'<h3>Send Wishlist to DFS: </h3>
	<div class="wishlist-form">
		<p class="center"><em>Submitting this form will send an email to our customer service department. <br/>
		Someone will then contact you to finalize the order.</em></p>
		<form method="post" action="wishlist.php">
			<fieldset>
				<p>Notes:</p><textarea rows="3" cols="50" name="message" ></textarea><br/><br/>';
					$email= $_SESSION['user'];	
					print("	<input type=\"hidden\" name=\"email\" value=\"".$email."\" />");
					print("<div class=\"captcha_center\">");
					//captcha
					//Go here for help editing captcha: http://recaptcha.net/plugins/php/
					require_once('includes/recaptchalib.php');
					require_once('config/recaptcha.config.inc');
					echo recaptcha_get_html($publickey);
					print("<br/></div>");
					$query="SELECT * FROM Wishlists where uid = '".$uid."' ORDER BY wname";
					$wishlists= $mysqli->query($query);			
					
					print("Select a wishlist to send: <select name=\"list\">");
	
					while ($list= $wishlists->fetch_assoc()) {
						if (isset($_GET['id']) || (isset($_POST['toggle']) && $_POST['toggle']=="Open Wishlist" && isset($_POST['wishlistid']))){
							//check to see if this wishlist id belongs to this user
							if (isset($_GET['id'])){
								$id=$_GET['id'];
							} else {
								$id=$_POST['wishlistid'];	
							}
							if ($list['wishlistid']==$id) {
								print("<option selected name=\"list\" value=\"".$list['wishlistid']."\">".$list['wname']."</option>");								
							} else {
								print("<option name=\"list\" value=\"".$list['wishlistid']."\">".$list['wname']."</option>");								
							}
						} else {
							print("<option name=\"list\" value=\"".$list['wishlistid']."\">".$list['wname']."</option>");		
						}
					}
					print("</select><br/><br/><span class=\"small\">The wishlist will be sent from the email address associated with your account.</span><br/>");	
				echo'<input type="submit" value="Send Wishlist" name="email_submit" />
			</fieldset>
		</form>
	</div>';
	
}
}

?>
<?php } else {
	print("<p>Please log in to view your wishlists...</p>");
} ?>
</div>
<?php
//Close the connection to the database
$mysqli->close();
include ('includes/footer.php');
?>
</body>
</html>